<template>
  <el-dialog :destroy-on-close="true" :before-close="onCancel" :lock-scroll="false" title="添加任务"
             :visible.sync="visible"
             width="950px">
    <el-form ref="form" :model="form" :rules="rules" label-width="auto">
<!--      <el-form-item label="任务名称：" prop="name">-->
<!--        <el-input v-model="form.name" placeholder="名称最多不超过50个字符"/>-->
<!--      </el-form-item>-->
      <el-form-item label="项目名称：" prop="project_id">
        <!--        <el-autocomplete v-model="projectName" :fetch-suggestions="onQueryProjectName" @select="onProjectSelect"-->
        <!--                         placeholder="请输入项目名称">-->
        <!--&lt;!&ndash;          <el-button slot="append" icon="el-icon-search"></el-button>&ndash;&gt;-->
        <!--        </el-autocomplete>-->
        <ProjectSelect :disabled="flag" :custom-options="projectOptions" @onProjectSelect="onProjectSelect"
                       v-model="form.project_id"/>
      </el-form-item>
      <el-form-item label="描述说明：" prop="description">
        <el-input v-model="form.description" placeholder="描述任务名称" type="textarea" :rows="4" show-word-limit
                  maxlength="100"></el-input>
      </el-form-item>
      <!--      <el-form-item label="任务余量：">-->
      <!--        {{ form.margin }}%-->
      <!--      </el-form-item>-->
      <el-form-item label="项目总工时：">
        {{ plan_work_hour }}h
      </el-form-item>
      <EditTable :table.sync="form.items" :type-list="typeList" ref="editTableRef"/>
    </el-form>
    <div slot="footer">
      <el-button @click="onCancel()">取消</el-button>
      <el-button :loading="loading" type="primary" @click="onSave('form')">保存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css';
import EditTable from "@/views/project/projectList/components/editTable.vue";
import ProjectSelect from "@/views/project/task/components/ProjectSelect.vue";

export default {
  name: "product-form",
  props: ['typeList'],
  components: {
    EditTable,
    ProjectSelect
  },
  data() {
    return {
      plan_work_hour: 0,
      flag: false,
      projectName: '',
      visible: false,
      rules: {
        name: [
          {required: true, message: "任务名称为必需", trigger: "blur"},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
        ],
        project_id: [{required: true, message: "项目名称为必需", trigger: "change"}]
      },
      form: {
        name: null,
        project_id: null,
        description: null,
        items: [],
        margin: 100
      },
      loading: false,
      projectOptions: [],
      margin: 100,
    }
  },
  mounted() {
  },
  watch: {
    'form.items': {
      handler(current) {
        current?.length && (this.form.margin = current.reduce((total, item) => (total -= item.percent), this.margin))
      },
      deep: true
    },
    'form.project_id': {
      handler() {
        this.form.items?.length ? this.form.margin = this.form.items.reduce((total, item) => (total -= item.percent), this.margin) : false
      },
      deep: true
    }
  },
  methods: {
    remoteMethod(query = '') {
      this.loading = true
      this.$http.get(`/user/index?limit=30&realname=${query} `).then((res) => {
        if (res.data.code == 0)
          this.options = res.data.data.filter(item => {
            return item.id !== 1 && item.position_id === 5
          })
        this.loading = false
      });
    },
    showDialog(row) {
      this.visible = true;
      this.$nextTick(() => {
        if (row) {
          this.plan_work_hour = row.plan_work_hour
          this.form.margin = row.percent_residue
          this.margin = row.percent_residue
          this.flag = true
          this.form.project_id = row.id
          this.projectOptions = [{id: row.id, name: row.name, percent_residue: row.percent_residue}]
        }
      })
    },
    onSave(val) {
      let flag = false
      let flag2 = false
      this.$refs[val].validate((valid) => {
        flag = valid
      });
      flag2 = this.$refs.editTableRef.validate()
      if (this.form.margin < 0) {
        return this.$message.error("任务余量不能小于0,请修改任务比重分配比例")
      }
      if (flag && flag2) {
        this.handleAddTask(this.form)
      }
    },
    onCancel() {
      this.form.margin = 100;
      this.margin = 100;
      this.visible = false;
      this.$refs['form'].resetFields();
    },
    onProjectSelect(val) {
      this.plan_work_hour = val
    },
    handleAddTask(params) {
      this.loading = true
      this.$http.post('/tasks', params).then(res => {
        if (res.data.code === 0) {
          this.$message.success(res.data.msg);
          this.onCancel();
          this.$emit("reload")
        } else {
          this.$message.error(res.data.msg);
        }
        this.loading = false;
      })
    },
  }
}
</script>

<style scoped>
.area /deep/ .el-cascader {
  width: 100%;
}

/deep/ .el-input {
  width: 100%;
}

/deep/ .el-autocomplete {
  width: 100%;
}

.el-dialog:not(.ele-dialog-form) .el-dialog__body .el-form .el-form-item:last-child {
  margin-bottom: 0;
}
</style>
